package org.dtrd.modules.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.dtrd.modules.patient.entity.po.DtrdEntRdPatient;
import org.dtrd.modules.patient.service.IDtrdEntRdPatientService;
import org.dtrd.modules.record.entity.po.*;
import org.dtrd.modules.record.service.*;
import org.dtrd.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * 旧记录导入接口
 * @author zcli
 * @date 2021-09-25
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileAPIController {
    private static Pattern isNumber=  Pattern.compile("^-?\\d+(\\.\\d+)?$");

    @Autowired
    private IDtrdEntRdPatientService patientService;
    @Autowired
    private ISugarRecordService sugarRecordService;
    @Autowired
    private IHeightWeightRecordService heightWeightRecordService;
    @Autowired
    private IKetoneRecordService ketoneRecordService;
    @Autowired
    private IWaistlineRecordService waistlineRecordService;
    @Autowired
    private IBloodPressureRecordService bloodPressureRecordService;

    /**
     * 导入旧记录
     * @param filePath
     * @return
     */
    @PutMapping("/inputOldData")
    public Map inputOldData(@RequestParam String filePath) {
        Map map = new HashMap();
        if (!Objects.equals(filePath, "")) {
            boolean bol = readExcelXlsFile(filePath);
            map.put("code", 1000);
            map.put("errMsg", "ok");
            map.put("data", bol);
        } else {
            map.put("code", 1001);
            map.put("errMsg", "error");
        }
        return map;
    }

    /**
     * 读取xls文件
     * @param
     */
    public boolean readExcelXlsFile(String filePath) {
//        String filePath = "D:\\work\\file\\out\\jialer\\逆糖\\患者日常血糖、血压记录.xls";
        File file = new File(filePath);
        try {
            if (file.isFile() && file.exists()) {
                FileInputStream fis = new FileInputStream(file);
                Workbook wb = new HSSFWorkbook(fis);
                int sheetNum = wb.getNumberOfSheets();
                Sheet sheet = null;
                int totalRow = 0;
                for (int i = 0; i < sheetNum; i++) {
                    log.info("------第{}个Sheet------", 1+i);
                    sheet = wb.getSheetAt(i);
                    int firstRowIndex = sheet.getFirstRowNum() + 1;
                    int lastRowIndex = sheet.getLastRowNum();
                    for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {
                        Row row = sheet.getRow(rIndex);
                        if (row != null) {
                            String pName = getCellNameValue(row.getCell(0));
                            Date date = getCellDateValue(row.getCell(1));

//                            log.info("=rIndex:{}, value:{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}", rIndex, pName, date, getCellValue(row.getCell(2)),
//                                    getCellValue(row.getCell(3)), getCellValue(row.getCell(4)), getCellValue(row.getCell(5)),
//                                    getCellValue(row.getCell(6)), getCellValue(row.getCell(7)), getCellValue(row.getCell(8)),
//                                    getCellValue(row.getCell(9)), getCellValue(row.getCell(10)), getCellValue(row.getCell(11)),
//                                    getCellValue(row.getCell(12)), getCellValue(row.getCell(13)), getCellValue(row.getCell(14)),
//                                    getCellValue(row.getCell(15)), getCellValue(row.getCell(16)));
                            // 查询患者信息
                            DtrdEntRdPatient patient = patientService.getOne(new QueryWrapper<DtrdEntRdPatient>().eq("patientsName", pName));
                            if (null != patient) {
                                int pId = patient.getDataId();
                                // 添加血糖 血糖记录：1-早餐前,2-早餐后,3-午餐前,4-午餐后,5-晚餐前,6-晚餐后,7-睡前,8-凌晨
                                addSugarValue(pId, date, getCellValue(row.getCell(2)), getCellValue(row.getCell(3)), getCellValue(row.getCell(4)),
                                        getCellValue(row.getCell(5)), getCellValue(row.getCell(6)), getCellValue(row.getCell(7)), getCellValue(row.getCell(8)));
                                // 添加身高体重
                                addHeightWeight(pId, date, getCellValue(row.getCell(9)));
                                // 添加尿酮
                                addKetone(pId, date, getCellValue(row.getCell(10)));
                                // 添加腰围
                                addWaistline(pId, date, getCellValue(row.getCell(11)));
                                // 添加血压和心率   血压：1-早晨， 2-晚上
                                addBloodPressure(pId, date, getCellValue(row.getCell(12)), getCellValue(row.getCell(13)), getCellValue(row.getCell(14)),
                                        getCellValue(row.getCell(15)), getCellValue(row.getCell(16)));
                            }
                            totalRow++;
                        }
                    }
                }
                log.info("------------totalRow-----------{}", totalRow);
            }
        } catch(FileNotFoundException e1){
            log.error("文件不存在");
        } catch(IOException e){
            log.error("读取文件异常");
        }
        return true;
    }

    // 添加血糖
    private int addSugarValue(int pId, Date date, Object s1, Object s2, Object s3, Object s4, Object s5, Object s6, Object s7) {
        if (StringUtil.StrTrimFloat(s1) >= 0.0f) {
            DtrdEntRdSigninSugarValue v1 = new DtrdEntRdSigninSugarValue();
            v1.setPatientId(pId);
            v1.setRecordDate(date);
            v1.setRecordTime(date);
            v1.setSugarValueTimeTypeId(1);
            v1.setSugarValueSugarValue(StringUtil.StrTrimFloat(s1));
            v1.setSugarValueSourceType(99);
            v1.setSugarValueType(0);
            v1.setCreateTime(new Date());
            v1.setIsDel(0);
            sugarRecordService.save(v1);
        }
        if (StringUtil.StrTrimFloat(s2) >= 0.0f) {
            DtrdEntRdSigninSugarValue v2 = new DtrdEntRdSigninSugarValue();
            v2.setPatientId(pId);
            v2.setRecordDate(date);
            v2.setRecordTime(date);
            v2.setSugarValueTimeTypeId(2);
            v2.setSugarValueSugarValue(StringUtil.StrTrimFloat(s2));
            v2.setSugarValueSourceType(99);
            v2.setSugarValueType(0);
            v2.setCreateTime(new Date());
            v2.setIsDel(0);
            sugarRecordService.save(v2);
        }
        if (StringUtil.StrTrimFloat(s3) >= 0.0f) {
            DtrdEntRdSigninSugarValue v3 = new DtrdEntRdSigninSugarValue();
            v3.setPatientId(pId);
            v3.setRecordDate(date);
            v3.setRecordTime(date);
            v3.setSugarValueTimeTypeId(3);
            v3.setSugarValueSugarValue(StringUtil.StrTrimFloat(s3));
            v3.setSugarValueSourceType(99);
            v3.setSugarValueType(0);
            v3.setCreateTime(new Date());
            v3.setIsDel(0);
            sugarRecordService.save(v3);
        }
        if (StringUtil.StrTrimFloat(s4) >= 0.0f) {
            DtrdEntRdSigninSugarValue v4 = new DtrdEntRdSigninSugarValue();
            v4.setPatientId(pId);
            v4.setRecordDate(date);
            v4.setRecordTime(date);
            v4.setSugarValueTimeTypeId(4);
            v4.setSugarValueSugarValue(StringUtil.StrTrimFloat(s4));
            v4.setSugarValueSourceType(99);
            v4.setSugarValueType(0);
            v4.setCreateTime(new Date());
            v4.setIsDel(0);
            sugarRecordService.save(v4);
        }
        if (StringUtil.StrTrimFloat(s5) >= 0.0f) {
            DtrdEntRdSigninSugarValue v5 = new DtrdEntRdSigninSugarValue();
            v5.setPatientId(pId);
            v5.setRecordDate(date);
            v5.setRecordTime(date);
            v5.setSugarValueTimeTypeId(5);
            v5.setSugarValueSugarValue(StringUtil.StrTrimFloat(s5));
            v5.setSugarValueSourceType(99);
            v5.setSugarValueType(0);
            v5.setCreateTime(new Date());
            v5.setIsDel(0);
            sugarRecordService.save(v5);
        }
        if (StringUtil.StrTrimFloat(s6) >= 0.0f) {
            DtrdEntRdSigninSugarValue v6 = new DtrdEntRdSigninSugarValue();
            v6.setPatientId(pId);
            v6.setRecordDate(date);
            v6.setRecordTime(date);
            v6.setSugarValueTimeTypeId(6);
            v6.setSugarValueSugarValue(StringUtil.StrTrimFloat(s6));
            v6.setSugarValueSourceType(99);
            v6.setSugarValueType(0);
            v6.setCreateTime(new Date());
            v6.setIsDel(0);
            sugarRecordService.save(v6);
        }
        if (StringUtil.StrTrimFloat(s7) >= 0.0f) {
            DtrdEntRdSigninSugarValue v7 = new DtrdEntRdSigninSugarValue();
            v7.setPatientId(pId);
            v7.setRecordDate(date);
            v7.setRecordTime(date);
            v7.setSugarValueTimeTypeId(7);
            v7.setSugarValueSugarValue(StringUtil.StrTrimFloat(s7));
            v7.setSugarValueSourceType(99);
            v7.setSugarValueType(0);
            v7.setCreateTime(new Date());
            v7.setIsDel(0);
            sugarRecordService.save(v7);
        }
        return 0;
    }
    // 添加身高体重
    public boolean addHeightWeight(int pId, Date date, Object s8) {
        if (StringUtil.StrTrimFloat(s8) >= 0.0f) {
            DtrdEntRdSigninHeightWeight v8 = new DtrdEntRdSigninHeightWeight();
            v8.setPatientId(pId);
            v8.setRecordDate(date);
            v8.setRecordTime(date);
            v8.setHeightWeightWeight(StringUtil.StrTrimFloat(s8));
            v8.setCreateTime(new Date());
            v8.setIsDel(0);
            return heightWeightRecordService.save(v8);
        }
        return false;
    }
    // 添加尿酮
    public boolean addKetone(int pId, Date date, Object s9) {
        if (StringUtil.StrTrimFloat(s9) >= 0.0f) {
            DtrdEntRdSigninKetone v9 = new DtrdEntRdSigninKetone();
            v9.setPatientId(pId);
            v9.setRecordDate(date);
            v9.setRecordTime(date);
            v9.setKetoneValue(StringUtil.StrTrimInt(s9));
            v9.setCreateTime(new Date());
            v9.setIsDel(0);
            return ketoneRecordService.save(v9);
        }
        return false;
    }
    // 添加腰围
    public boolean addWaistline(int pId, Date date, Object s10) {
        if (StringUtil.StrTrimFloat(s10) >= 0.0f) {
            DtrdEntRdSigninWaistline v10 = new DtrdEntRdSigninWaistline();
            v10.setPatientId(pId);
            v10.setRecordDate(date);
            v10.setRecordTime(date);
            v10.setWaistlineValue(StringUtil.StrTrimInt(s10));
            v10.setCreateTime(new Date());
            v10.setIsDel(0);
            return waistlineRecordService.save(v10);
        }
        return false;
    }
    // 添加血压和心率
    public boolean addBloodPressure(int pId, Date date, Object s11, Object s12, Object s13, Object s14, Object s15) {
        boolean result = false;
        if (StringUtil.StrTrimFloat(s11) >= 0.0f || StringUtil.StrTrimFloat(s12) >= 0.0f || StringUtil.StrTrimFloat(s15) >= 0.0f) {
            DtrdEntRdSigninBloodPressure v11 = new DtrdEntRdSigninBloodPressure();
            v11.setPatientId(pId);
            v11.setRecordDate(date);
            v11.setRecordTime(date);
            v11.setBloodPressureType(1);
            v11.setBloodPressureHighPressure(StringUtil.StrTrimInt(s11));
            v11.setBloodPressureLowVoltage(StringUtil.StrTrimInt(s12));
            v11.setBloodPressureHeartRate(StringUtil.StrTrimInt(s15));
            v11.setCreateTime(new Date());
            v11.setIsDel(0);
            result = bloodPressureRecordService.save(v11);
        }
        if (StringUtil.StrTrimFloat(s13) >= 0.0f || StringUtil.StrTrimFloat(s14) >= 0.0f) {
            DtrdEntRdSigninBloodPressure v110 = new DtrdEntRdSigninBloodPressure();
            v110.setPatientId(pId);
            v110.setRecordDate(date);
            v110.setRecordTime(date);
            v110.setBloodPressureType(2);
            v110.setBloodPressureHighPressure(StringUtil.StrTrimInt(s13));
            v110.setBloodPressureLowVoltage(StringUtil.StrTrimInt(s14));
            v110.setBloodPressureHeartRate(0);
            v110.setCreateTime(new Date());
            v110.setIsDel(0);
            result = bloodPressureRecordService.save(v110);
        }
        return result;
    }

    // 获取日期
    public Date getCellDateValue(Cell cell) {
        Date ret ;
        if (null != cell) {
            try {
                ret = cell.getDateCellValue();
            } catch (Exception e) {
                ret = null;
            }
        } else {
            ret = null;
        }
        return ret;
    }
    // 获取名字
    public String getCellNameValue(Cell cell) {
        String ret ;
        if (null != cell) {
            try {
                ret = cell.getStringCellValue();
            } catch (Exception e) {
                ret = "";
            }
        } else {
            ret = "";
        }
        return ret;
    }

    // 获取其他测量值
    public Object getCellValue(Cell cell) {
        Object ret = "";
        if (null != cell) {
            switch (cell.getCellType()) {
                case BLANK:
                case ERROR:
                    ret = 0.0f;
                    break;
                case STRING:
                    ret = cell.getStringCellValue();
                    if (!isNumber(String.valueOf(ret))) {
                        ret = 0.0f;
                    }
                    break;
                case NUMERIC:
                    ret = cell.getNumericCellValue();
                    if (!isNumber(String.valueOf(ret))) {
                        ret = 0.0f;
                    }
                    break;
                case BOOLEAN:
                    ret = cell.getBooleanCellValue();
                    break;
                case FORMULA:
                    try {
                        ret = cell.getDateCellValue();
                    } catch (Exception e) {
                        //log.error("****************{}", cell.getCellFormula());
                        ret = cell.getCellFormula();
                        if (!isNumber(String.valueOf(ret))) {
                            ret = 0.0f;
                        }
                    }
                    break;
                default:
                    ret = cell.getStringCellValue();
                    if (!isNumber(String.valueOf(ret))) {
                        ret = 0.0f;
                    }
                    break;
            }
        } else {
            ret = "";
        }
        return ret;
    }


    /**
     * format cell value
     * @param string
     * @return
     */
    public Float formatCell(String string) {
        if(StringUtils.isBlank(string)){
            return 0.0f;
        }
        if (!isNumber.matcher(string).matches()) {
            return 0.0f;
        }
        return Float.valueOf(string);
    }

    /**
     * 验证是否非数字
     */
    public boolean isNumber(String string) {
        if(StringUtils.isBlank(string)){
            return false;
        }
        return isNumber.matcher(string).matches();
    }

}
